//
//  HTViewModel.swift
//  weibo
//
//  Created by JonsonLiu on 16/4/20.
//  Copyright © 2016年 liujonson. All rights reserved.
//

import UIKit
import SVProgressHUD
class HTViewModel: NSObject {

    
    static var sharedViewModel : HTViewModel = HTViewModel()
    
    override init() {
        super.init()
        
        account = self.accountInsanBox()
        
        print(account)
        
        print(self.accountInsanBox())
    }
    
    var account : HTAccountModel?
    
    var accessToken : String?{
        
        return self.account?.access_token
    }
    
    
    var isLog : Bool{
        
        
        if accessToken == nil {
        
            return false
        }
        
        guard let expiresDate = self.account?.expiresDate else{
            
            print(self.account?.expiresDate)
            
            return false
        
        }
        
        if NSDate().compare(expiresDate) == .OrderedAscending{
        
            return true
        }
        
        return false
    }
    
    
    
    
    func loadAccessToken(code:String , finish:(isSuccess : Bool) -> ()){
        
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        
        let params = [
            "client_id": WB_APP_KEY,
            "client_secret": WB_APP_SECRET,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WB_REDIRECT_URI
        ]
        
        NetworkTools.sharedTools.request(.Post, urlString: urlString, parameters: params) { (responseObject, error) -> () in
            
            
            if error != nil{
                
                print("error")
                
                finish(isSuccess: false)
                return
            }
            print(responseObject)
            guard let dict = responseObject as? [String : AnyObject] else{
                
                
                finish(isSuccess: false)
                return
            }
            
            let account = HTAccountModel(dict : dict)
            
            print(account)
            

            
            self.loadUserinfo(account, finish: finish)
        }
    }
    
    
    //获取个人信息
     func loadUserinfo(account : HTAccountModel , finish:(isSuccess : Bool) -> ()){
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let params = [
            
            "access_token": account.access_token ?? "",
            "uid": account.uid ?? ""
            
        ]
        
        NetworkTools.sharedTools.request(.Get, urlString: urlString, parameters: params) { (responseObject, error) -> () in
            
            if error != nil{
                
                print(error)
                
                finish(isSuccess : false)
                
                print("error错误")
                
                return
            }
            
//            print(responseObject)
            
            guard let dict = responseObject as? [String : AnyObject] else{
                
                finish(isSuccess : false)
                print("格式不对")
                return
            }
            
            account.name = dict["name"] as? String
            account.avatar_large = dict["avatar_large"] as? String
            
            print(account)
            
            self.account = account
            
            self.saveAccount(account)
            
            finish(isSuccess : true)
           
        }
        
    }
    
    
    
    //保存个人信息
    private func saveAccount(account : HTAccountModel){
        
        let  path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.archive")
        
        print(path)
        
        NSKeyedArchiver.archiveRootObject(account, toFile: path)
        
        
    }
    
    //去沙盒中读取
    private func accountInsanBox() -> HTAccountModel?{
        
        let  path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.archive")
        
        let  result = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? HTAccountModel
        
        return result
    }
    
        func webViewDidStartLoad(webView: UIWebView) {
    
            SVProgressHUD.show()
            SVProgressHUD.setMinimumDismissTimeInterval(3)
        }
    
        func webViewDidFinishLoad(webView: UIWebView) {
            SVProgressHUD.dismiss()
            SVProgressHUD.setMinimumDismissTimeInterval(3)
            
        }
    

    
}
